package ans.p235;

import ans.base.TreeNode;

/**
 * #      235
 * 名称   二叉搜索树的最近公共祖先
 * 链接   https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-search-tree
 * 题解   [755](https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-search-tree/solution)
 * 通过率 66.2%
 * 难道   简单
 */

public class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        TreeNode ancestor = root;
        while (true) {
            if (p.val < ancestor.val && q.val < ancestor.val) {
                ancestor = ancestor.left;
            } else if (p.val > ancestor.val && q.val > ancestor.val) {
                ancestor = ancestor.right;
            } else {
                break;
            }
        }
        return ancestor;
    }

}
